package com.cby.springboot.demo.controller;

import com.cby.springboot.demo.bean.*;
import com.cby.springboot.demo.service.AdminPermissionService;
import com.cby.springboot.demo.service.AdminRoleService;
import com.cby.springboot.demo.service.AdminUserRoleService;
import com.cby.springboot.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/api")
public class AdminController extends BaseController{

    @Autowired
    UserService userService;

    @Autowired
    AdminRoleService adminRoleService;

    @Autowired
    AdminUserRoleService adminUserRoleService;

    @Autowired
    AdminPermissionService adminPermissionService;

    @CrossOrigin
    @GetMapping("/admin/user")
    @ResponseBody
    public List<AdminUser> listUsers() throws Exception {
        return list();
    }

    public List<AdminUser> list() {
        List<User> users = userService.getAllUsers();

        // 转换所有的用户
        List<AdminUser> adminUserList = new ArrayList<>();
        if(users != null && !users.isEmpty()) {
            logI(users.toString());
            for (User user : users) {
                adminUserList.add(AdminUser.convert(user));
            }
        }

        logI(adminUserList.toString());

        adminUserList.forEach(u -> {
            List<AdminRole> roles = listRolesByUser(u.getUserName());
            u.setRoles(roles);
        });

        return adminUserList;
    }

    public List<AdminRole> listRolesByUser(String username) {
        String uid = userService.getByUserName(username).getUserId();
        List<Integer> rids = adminUserRoleService.findAllByUid(uid)
                .stream().map(AdminUserRole::getRid).collect(Collectors.toList());
        return listAllByRids(rids);
    }

    private List<AdminRole> listAllByRids(List<Integer> rids){
        int size = rids == null ? 0 : rids.size();
        List<AdminRole> adminRoles = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            adminRoles.add(adminRoleService.findById(rids.get(i)));
        }
        return adminRoles;
    }

    public boolean needFilter(String requestAPI) {
        List<AdminPermission> ps = adminPermissionService.findAll();
        for (AdminPermission p: ps) {
            if (p.getUrl().equals(requestAPI)) {
                return true;
            }
        }
        return false;
    }

}
